package com.kdg.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by kong on 2017/7/27.
 * 用于解决多线程安全问题的方式:
 * 1.synchronized:同步代码块  同步方法  (隐式锁)
 * 2.同步锁Lock(显式锁)   通过lock()方法上锁  unlock()方法解锁
 */
public class TestLock {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(ticket,"1号窗口").start();
        new Thread(ticket,"2号窗口").start();
        new Thread(ticket,"3号窗口").start();
    }

    public boolean test(){
        try {
            Thread.sleep(200);
            return true;
        } catch (Error e) {
            e.printStackTrace();
            return false;
        }catch (RuntimeException e) {
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

class Ticket implements Runnable{

    private int tick = 100;
    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while(true){
            lock.lock();
            try {
                if(tick>0){
                    try {
                        Thread.sleep(200);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + "完成售票,余票为:"+(--tick));
            } finally {
                lock.unlock();
            }
        }
    }
}

